<template>
  <div class="tree-container">
    <TreeDraggable 
      :nodes="treeData" 
      group="tree-nodes" 
      :level="0" 
      :dragging="dragging" 
      @node-dragged="nodeDragged" 
      @changeDragging="changeDragging" 
      parent-id="0"/>
  </div>
</template>

<script>
import TreeDraggable from './TreeDraggable.vue';

export default {
  components: {
    TreeDraggable
  },
  data() {
    return {
      treeData: [
        {
          id: 1,
          label: 'Level 1',
          children: [
            {
              id: 11,
              label: 'Level 1-1',
              children: [
                {
                  id: 111,
                  label: 'Level 1-1-1'
                }
              ]
            }
          ]
        },
        {
          id: 2,
          label: 'Level 2',
          children: [
            {
              id: 21,
              label: 'Level 2-1',
              children: [
                {
                  id: 211,
                  label: 'Level 2-1-1'
                }
              ]
            }
          ]
        },
        {
          id: 3,
          label: 'Level 3',
          children: [
            {
              id: 31,
              label: 'Level 3-1',
              children: [
                {
                  id: 311,
                  label: 'Level 3-1-1'
                }
              ]
            }
          ]
        }
      ],
      dragging: false
    };
  },
  methods: {
    getNodeById(tree, targetId) {
      // 遍历当前层级的所有节点
      for (let node of tree) {
        // 检查当前节点的 id 是否匹配
        if (node.id == targetId) {
          return node;
        } else if (node.children && node.children.length > 0) {
          // 递归检查子节点
          const result = this.getNodeById(node.children, targetId);
          if (result) {
            return result;
          }
        }
      }
      // 如果未找到，返回 null
      return null;
    },
    nodeDragged(data) {
      const { level, index, newLevel, newDraggableIndex, sourceParentId, targetParentId } = data;
      const sourceParent = this.getNodeById(this.treeData, sourceParentId);
      let sourceNode;
      if (sourceParent) {
        sourceNode = sourceParent.children.splice(index, 1)[0];
      } else {
        sourceNode = this.treeData.splice(index, 1)[0];
      }
      const targetParent = this.getNodeById(this.treeData, targetParentId);
      if (!targetParent) {
        this.treeData.splice(newDraggableIndex, 0, sourceNode);
      } else {
        targetParent.children.splice(newDraggableIndex, 0, sourceNode);
        targetParent.children = targetParent.children.filter(c => c.move !== false);
      }
      if (sourceParent && !sourceParent.children.length) {
        sourceParent.children.push({
          id: Math.random(),
          label: '请拖动至此处',
          move: false
        });
      }
      console.log('Node dragged 0', data);
    },
    changeDragging(flag) {
      this.dragging = flag;
    }
  }
};
</script>
